#include "../ocl/buffer.h"


int ocl_buffer_load(ocl_buffer  *buffer,
					ocl_context *context,
					cl_mem_flags flags,
					size_t       size,
					void        *host_ptr)
{
	static const char fn[] = "[ocl_buffer_load]";
	assert( buffer );
	assert( context );
	
	ocl_errno  = CL_SUCCESS;
	memset( buffer, 0, sizeof(buffer) );
	if( ocl_logfile ) fprintf( ocl_logfile, "%s <%u>\n", fn, (unsigned) size );
	buffer->handle = clCreateBuffer( context->handle, flags, size, host_ptr, & ocl_errno);
	if( CL_SUCCESS != ocl_errno )
	{
		goto ERROR;
	}
	
#define OCL_BUFFER_INFO(FIELD,TYPE) \
if( CL_SUCCESS != ( ocl_errno = clGetMemObjectInfo( buffer->handle, CL_MEM_##FIELD, sizeof(TYPE), & buffer->FIELD, NULL) ) ) goto ERROR; else \
if( ocl_logfile ) fprintf( stderr, "%s %s = %u\n", fn, #FIELD, (unsigned) ( buffer->FIELD ) )
	
	OCL_BUFFER_INFO(FLAGS,cl_mem_flags);
	OCL_BUFFER_INFO(SIZE,size_t);
	
	return 0;
	
ERROR:
	ocl_buffer_quit( buffer );
	return -1;
}

void ocl_buffer_quit( ocl_buffer *buffer )
{
	if( buffer )
	{
		(void) clReleaseMemObject( buffer->handle );
		memset( buffer, 0, sizeof(ocl_buffer) );
	}
}
